const query = require('../config/sql')
const config = require('../config/baseConfig')
const getCommentTree = require('../utils/getCommentTree')
const axios = require('axios');
const jwt = require('jsonwebtoken')
const qiniu = require('qiniu')
const { v4: uuidv4 } = require('uuid');
const dayjs = require('dayjs')
const { getToken } = require('../api/index')
const createagreement = require('../utils/createagreement')
const createpermissions = require('../utils/createpermission')
const findUser = async (username) => {
        const sql = `select * from users where username="${username}";`;
        const result = await query(sql);
        return result;
}

const user = {
        login: async (ctx, next) => {
                const { username, password } = ctx.request.body;
                const flag = await findUser(username);
                if (!flag.length) {
                        try {
                                ctx.body = {
                                        code: 211,
                                        message: '用户不存在!'
                                }
                        } catch (error) {
                                console.log(error);
                        }
                        return
                } else {
                        const sql = `select * from users where username="${username}" and password="${password}";`
                        await query(sql).then(async response => {
                                if (response.length != 0) {
                                        const data = response[0]
                                        const id = data.user_id
                                        const sql = `select * from permissions where user_id="${id}";`
                                        await query(sql).then(result => {
                                                if (result.length != 0) {
                                                        data.permissions = {
                                                                publish: result[0].publish == 1,
                                                                comment: result[0].comment == 1,
                                                                approval: result[0].approval == 1,
                                                        }

                                                }

                                        })
                                        const accessToken = getToken({ id, username }, true)
                                        ctx.body = {
                                                code: 200,
                                                message: '登录成功',
                                                data: data,
                                                accessToken: `Bearer ${accessToken}`
                                        }
                                } else {
                                        ctx.body = {
                                                code: 201,
                                                message: '密码错误'
                                        }
                                }
                        })
                }

        },
        getuserInfo:async (ctx,next)=>{
                const { user_id } = ctx.request.body;
                const sql = `select * from users where user_id="${user_id}";`
                await query(sql).then(async response => {
                        if (response.length != 0) {
                                const data = response[0]
                                const sql = `select * from permissions where user_id="${user_id}";`
                                await query(sql).then(result => {
                                        if (result.length != 0) {
                                                data.permissions = {
                                                        publish: result[0].publish == 1,
                                                        comment: result[0].comment == 1,
                                                        approval: result[0].approval == 1,
                                                }
                                        }

                                })
                                ctx.body = {
                                        code: 200,
                                        data: data
                                }
                        } else {
                                ctx.body = {
                                        code: 201,
                                        data: {}
                                }
                        }
                })
        },
        register: async (ctx, next) => {
                const { username, password } = ctx.request.body;
                const flag = await findUser(username);
                if (flag.length) {
                        ctx.body = {
                                code: 200,
                                message: '用户已存在！'
                        }
                        return
                } else {
                        const id = uuidv4();
                        const values = [id, username, password, dayjs(new Date().getTime()).format('YYYY-MM-DDTHH:mm:ssZ')]
                        const sql = `insert into users(user_id,username,password,registerTime) values(?,?,?,?);`;
                        await query(sql, values).then(async(response) => {
                                if (response.affectedRows == 1) {
                                      await  createpermissions(id).then(response => {
                                                ctx.body = {
                                                        code: 200,
                                                        message: '注册成功！'
                                                }
                                        })
                                }
                        }).catch(err => {
                                ctx.body = {
                                        code: 501,
                                        message: err
                                }
                        })
                }

                return
        },
        RealName_Authentication: async (ctx, next) => {
                const requestUrl = 'http://idenauthen.market.alicloudapi.com/idenAuthentication'
                const appcode = '0264a503f03740798e84382b5dc22f39'
                const { name, idNo, user_id } = ctx.request.body
                await axios({
                        method: 'post',
                        url: requestUrl,
                        params: {
                                name,
                                idNo
                        },
                        headers: {
                                'Authorization': 'APPCODE ' + appcode, // 添加headers  
                        }

                }).then(async (res) => {
                        if (res.data.respCode == '0000') {
                                const sql = `update users set realname="${name}",idNo="${idNo}" where user_id="${user_id}";`
                                await query(sql).then(result => {
                                        if (result.affectedRows) {
                                                ctx.body = {
                                                        code: 200,
                                                        message: '实名认证成功'
                                                }
                                        } else {
                                                ctx.body = {
                                                        code: 500,
                                                        message: '实名认证失败，请稍后再试'
                                                }
                                        }
                                })
                        } else if (res.data.respCode == '0007') {
                                ctx.body = {
                                        code: 500,
                                        message: '无此身份证号码，请稍后再试'
                                }
                        } else if (res.data.respCode == '0008') {
                                ctx.body = {
                                        code: 500,
                                        message: '身份证信息不匹配，请稍后再试'
                                }
                        }
                })
        },
        getUptoken: async (ctx, next) => {
                let ak = 'cBi0vN5F0OqXl0UDpT8d6nfyNHG7u51pzs2BWFb8'
                let sk = 'Eth2jFdyfcSrhiGf64u99iN9W26MGMI5RNsIFjTr'
                let bucket = 'myover'

                let mac = new qiniu.auth.digest.Mac(ak, sk);
                let option = {
                        scope: bucket,
                        expires: 3600 * 24
                }
                let putPolicy = new qiniu.rs.PutPolicy(option)
                let upToken = putPolicy.uploadToken(mac);

                if (upToken) {
                        ctx.body = {
                                code: 200,
                                upToken: upToken,

                        }
                } else {
                        ctx.body = {
                                code: 201
                        }
                }
        },
        publish: async (ctx, next) => {
                const token = ctx.request.headers.authorization.slice(7);
                const { ImgList, name, remark, type, age, gender, postsType } = ctx.request.body;
                if (postsType == 'pet') {
                        let ImgUrl = ImgList[0];
                        if (ImgList.length > 1) {
                                ImgUrl = ImgList.join('=');
                        }

                        const userInfo = jwt.verify(token, config.secret);
                        const information = await query(`select nickname,avatar,user_id from users where username=${userInfo.username};`);
                        const _id = uuidv4();
                        const sql = `insert into cardlist(card_id,publisher_id,name,remark,imgUrl,type,nickname,avatar,age,gender) values(?,?,?,?,?,?,?,?,?,?);`;
                        await query(sql, [_id, information[0].user_id, name, remark, ImgUrl, type, information[0].nickname, information[0].avatar, age, gender]).then(result => {
                                if (result) {
                                        ctx.body = {
                                                code: 200,
                                                message: '发布成功'
                                        }
                                } else {
                                        ctx.body = {
                                                code: 201,
                                                message: '发布失败，请稍后再试'
                                        }
                                }
                        }
                        );
                } else {

                        let ImgUrl = ImgList[0] || '';
                        if (ImgList.length > 1) {
                                ImgUrl = ImgList.join('=');
                        }
                        const userInfo = jwt.verify(token, config.secret);
                        const _id = uuidv4();
                        const information = await query(`select nickname,avatar,user_id from users where username=${userInfo.username};`);
                        const sql = `insert into shareposts(shareposts_id, sharer_id, imgUrl, like_count, title, content, collect_count,nickname,avatar) values(?,?,?,?,?,?,?,?,?);`;
                        await query(sql, [_id, information[0].user_id, ImgUrl, 0, name, remark, 0, information[0].nickname, information[0].avatar]).then(res => {
                                if (res) {
                                        ctx.body = {
                                                code: 200,
                                                message: '发布成功'
                                        }
                                } else {
                                        ctx.body = {
                                                code: 201,
                                                message: '发布失败，请稍后再试'
                                        }
                                }
                        })
                }


        },
        delPublish: async (ctx, next) => {
                const { card_id } = ctx.request.body;
                const sql = `delete from cardlist where card_id="${card_id}";`;
                await query(sql).then(result => {
                        if (result) {
                                ctx.body = {
                                        code: 200,
                                        message: '删除成功！'
                                }
                        } else {
                                ctx.body = {
                                        code: 500,
                                        message: '删除失败，请稍后再试'
                                }
                        }
                }
                );
        },
        getCardList: async (ctx, next) => {
                const sql = `select * from cardlist;`
                if (ctx.request.body.id) {
                        sql = `select * from cardlist where id=${ctx.request.body.id};`
                }
                await query(sql).then(res => {
                        let data = []
                        res.forEach(item => {
                                let url = item.imgUrl.split('=');
                                let obj = {
                                        card_id: item.card_id,
                                        publisher_id: item.publisher_id,
                                        avatar: item.avatar,
                                        imgUrl: url,
                                        nickname: item.nickname,
                                        name: item.name,
                                        remark: item.remark,
                                        state: item.state,
                                        type: item.type,
                                        age: item.age,
                                        gender: item.gender
                                }
                                data.push(obj)
                        });

                        ctx.body = {
                                code: 200,
                                data: data
                        }
                }).catch(err => {
                        console.log('err', err);
                });

        },
        searchList: async (ctx, next) => {

        },
        getChatInfo: async (ctx, next) => {
                const { chatId } = ctx.request.body
                await query(`select * from users where user_id="${chatId}";`).then(result => {
                        if (result.length > 0) {
                                const data = {
                                        user_id: result[0].user_id,
                                        nickname: result[0].nickname,
                                        gender: result[0].gender,
                                        birthday: result[0].birthday,
                                        avatar: result[0].avatar,
                                        registerTime: result[0].registerTime,
                                        brief_intro: result[0].brief_intro
                                }
                                ctx.body = {
                                        code: 200,
                                        data: data
                                }
                        }

                })
        },
        addAttention: async (ctx, next) => {
                const { follower_Id, userId, isattent } = ctx.request.body;
                let sql = `insert into user_relationship(user_id,follower_id) values(?,?);`
                if (isattent) {
                        sql = `delete from user_relationship where user_id=? and follower_id=?;`
                }
                const values = [userId, follower_Id]
                await query(sql, values).then(res => {
                        if (res.affectedRows == 1) {
                                if (isattent) {
                                        ctx.body = {
                                                code: 200,
                                                message: '取消成功！'
                                        }
                                } else {
                                        ctx.body = {
                                                code: 200,
                                                message: '关注成功！'
                                        }
                                }

                        }
                })

        },
        getCardCommentByCardId: async (ctx, next) => {
                const { card_id } = ctx.request.body;
                let sql = `SELECT c.comment_id, c.content,c.parent_comment_id, c.timestamp, c.like_count , c.reply_count,
                           u.nickname , u.avatar, c.user_id
                           FROM commentinfo c
                           JOIN users u ON c.user_id = u.user_id
                           WHERE c.card_id = "${card_id}" and c.parent_comment_id is null;`
                await query(sql).then(async res => {
                        await getCommentTree(res).then(data => {
                                ctx.body = {
                                        code: 200,
                                        data,
                                        message: ''
                                }
                        })

                }).catch(err => {
                        ctx.body = {
                                code: 500,
                                data: err,
                                message: '服务器错误'
                        }
                })

        },
        pubComment: async (ctx, next) => {
                const { user_id,
                        card_id,
                        content,
                        timestamp,
                        like_count,
                        reply_count,
                        parent_comment_id } = ctx.request.body;
                const comment_id = uuidv4();
                let sql = `INSERT INTO commentinfo (
                        user_id,
                        card_id,
                        content,
                        timestamp,
                        like_count,
                        reply_count,
                        comment_id,
                        parent_comment_id
                    ) values(?,?,?,?,?,?,?,?);`
                await query(sql, [
                        user_id,
                        card_id,
                        content,
                        timestamp,
                        like_count,
                        reply_count,
                        comment_id,
                        parent_comment_id
                ]).then(res => {
                        if (res.affectedRows == 1) {
                                ctx.body = {
                                        code: 200,
                                        message: ''
                                }
                        } else {
                                ctx.body = {
                                        code: 500,
                                        message: '评论失败，请稍后再试！'
                                }
                        }
                })

        },
        delComment: async (ctx, next) => {
                const { comment_id } = ctx.request.body;
                const sql = `delete from commentinfo where comment_id=?;`;
                await query(sql, [comment_id]).then(res => {
                        if (res.affectedRows == 1) {
                                ctx.body = {
                                        code: 200,
                                        message: '删除成功！'
                                }
                        } else {
                                ctx.body = {
                                        code: 500,
                                        message: '删除失败，请稍后再试！'
                                }
                        }
                })

        },
        searchByKeyWord: async (ctx, next) => {
                let keyword = ctx.request.body.keyword;
                const sql = `SELECT *  FROM cardList WHERE name LIKE CONCAT('%', ?, '%') OR gender = ? OR type = ? OR remark LIKE CONCAT('%', ?, '%');`
                await query(sql, [keyword, keyword, keyword, keyword]).then(res => {
                        let data = []
                        res.forEach(item => {
                                let obj = {
                                        ...item,
                                        imgUrl: item.imgUrl.split('=')
                                }
                                data.push(obj)
                        });
                        ctx.body = {
                                code: 200,
                                msg: 'success',
                                data
                        }
                })
        },
        approval: async (ctx, next) => {
                let { age, area, approvaler_id, gender, hasExperience, maritalStatus, occupation, petId, toapplicant, applicant_id } = ctx.request.body;
                const id = uuidv4();
                const status = 0;
                const sql = `insert into approvallist(approval_id,age,area,gender,hasExperience,maritalStatus,occupation,petId,approvaler_id,applicant_id,toapplicant,status) values(?,?,?,?,?,?,?,?,?,?,?,?);`;
                await query(sql, [id, age, area, gender, hasExperience, maritalStatus, occupation, petId, approvaler_id, applicant_id, toapplicant, status]).then(res => {
                        if (res) {
                                ctx.body = {
                                        code: 200,
                                        message: '申请成功'
                                }
                        } else {
                                ctx.body = {
                                        code: 201,
                                        message: '申请失败，请稍后再试'
                                }
                        }
                })
        },
        getapprovalList: async (ctx, next) => {
                let { id, type } = ctx.request.body;
                let sql;
                sql = type !== 'approval' ?
                        `SELECT approvallist.*, users.avatar, users.nickname,cardlist.name
                 FROM approvallist
                 JOIN users ON approvallist.approvaler_id = users.user_id
                 JOIN cardlist ON approvallist.petId = cardlist.card_id
                 WHERE approvallist.approvaler_id = ?;`
                        : `SELECT approvallist.*, users.avatar, users.nickname,cardlist.name
                 FROM approvallist
                 JOIN users ON approvallist.approvaler_id = users.user_id
                 JOIN cardlist ON approvallist.petId = cardlist.card_id
                 WHERE approvallist.applicant_id = ?;`
                await query(sql, [id]).then(res => {
                        if (res) {
                                ctx.body = {
                                        code: 200,
                                        data: res,
                                        message: null
                                }
                        } else {
                                ctx.body = {
                                        code: 201,
                                        message: '申请失败，请稍后再试'
                                }
                        }
                })
        },
        setApprovalStatus: async (ctx) => {
                let { id, status, reason = '' } = ctx.request.body;
                if (status == 1) {
                        createagreement({ id: id })
                }
                let sql1 = `update approvallist set status="${status}",reason="${reason}" where approval_id="${id}";`;
                await query(sql1).then(res => {
                        if (res.affectedRows) {
                                ctx.body = {
                                        code: 200,
                                        message: '审批成功'
                                }
                        } else {
                                ctx.body = {
                                        code: 500,
                                        message: '审批失败，请稍后再试'
                                }
                        }
                })
        },
        getapprovalDetail: async (ctx) => {
                let { id } = ctx.request.body;
                let sql = `select * from approvallist where approval_id=?;`;
                await query(sql, [id]).then(res => {
                        if (res) {
                                ctx.body = {
                                        code: 200,
                                        data: res
                                }
                        } else {
                                ctx.body = {
                                        code: 500,
                                        msg: '查询失败'
                                }
                        }
                })
        },
        cancelApproval: async (ctx) => {
                let { id } = ctx.request.body;
                let sql = `delete from approvallist where approval_id=?;`;
                await query(sql, [id]).then(res => {
                        if (res) {
                                ctx.body = {
                                        code: 200,
                                        data: null,
                                        message: '撤回成功！'
                                }
                        } else {
                                ctx.body = {
                                        code: 500,
                                        msg: '撤回失败，请稍后再试！'
                                }
                        }
                })
        },
        getagreementList: async (ctx, next) => {
                let { id } = ctx.request.body;
                let sql = `select * from agreement where sender_id="${id}" or adapt_id="${id}"`;
                if (id == '' || id == null) {
                        sql = `select * from agreement`;
                }

                await query(sql).then(result => {
                        if (result) {
                                ctx.body = {
                                        code: 200,
                                        data: result,
                                }
                        }
                })
        },
        getagreementDetail: async (ctx, next) => {
                let { id } = ctx.request.body;
                const sql = `SELECT   
                a.*,  
                u1.username AS senderPhone,  
                u1.nickname AS senderName,  
                u2.username AS receiverPhone,  
                u2.nickname AS receiverName,  
                c.gender as petGender,  
                c.age as petAge,  
                c.name AS pet_name
            FROM   
                agreement a  
            JOIN   
                users u1 ON a.sender_id = u1.user_id  
            JOIN   
                users u2 ON a.adapt_id = u2.user_id  
            LEFT JOIN   
                cardlist c ON a.pet_id = c.card_id
            WHERE   
                a.approval_id = ?; `
                await query(sql, [id]).then(result => {
                        if (result) {
                                ctx.body = {
                                        code: 200,
                                        data: result[0]
                                }
                        }
                })
        },
        updateSign: async (ctx, next) => {
                let { image, type, id } = ctx.request.body;
                const sql = type == 'adapt_sign' ? `update agreement set adapt_sign=? where agreement_id=?;` : `update agreement set sender_sign=? where agreement_id=?;`;
                await query(sql, [image, id]).then(result => {
                        if (result) {
                                ctx.body = {
                                        code: 200,
                                        data: null,
                                        message: '签名成功！'
                                }
                        }
                })
        },
        getShareList: async (ctx, next) => {
                const sql = `select * from shareposts;`
                /* if (ctx.request.body.id) {
                        sql = `select * from shareposts where id=${ctx.request.body.id};`
                } */
                await query(sql).then(res => {
                        let data = []
                        res.forEach(item => {
                                let url = []
                                if (item.imgUrl !== '') {
                                        url = item.imgUrl.split('=');
                                }

                                let obj = {
                                        shareposts_id: item.shareposts_id,
                                        sharer_id: item.sharer_id,
                                        avatar: item.avatar,
                                        imgUrl: url,
                                        nickname: item.nickname,
                                        like_count: item.like_count,
                                        content: item.content,
                                        title: item.title,
                                        collect_count: item.collect_count,
                                }
                                data.push(obj)
                        });

                        ctx.body = {
                                code: 200,
                                data: data
                        }
                }).catch(err => {
                        console.log('err', err);
                });

        },
        handlecollection: async (ctx, next) => {
                let { user_id, resource_id, resource_type, iscollection } = ctx.request.body;
                const id = uuidv4()
                const sql = iscollection ? `insert into collection(id,user_id, resource_type, resource_id) values(?,?,?,?);` : `delete from collection where user_id="${user_id}" and resource_type="${resource_type}" and resource_id="${resource_id}";`
                await query(sql, [id, user_id, resource_type, resource_id]).then(async result => {
                        if (result.affectedRows > 0) {
                                if (resource_type == 'share') {
                                        const sql1 = !iscollection ? `UPDATE shareposts SET collect_count = collect_count - 1 WHERE shareposts_id ="${resource_id}"` : `UPDATE shareposts SET collect_count = collect_count + 1 WHERE shareposts_id = "${resource_id}"`;
                                        await query(sql1).then(result => {
                                                if (result.affectedRows > 0) {
                                                        ctx.body = {
                                                                message: iscollection ? '收藏成功！' : '取消收藏成功！',
                                                                code: 200
                                                        }
                                                } else {
                                                        ctx.body = {
                                                                msg: '收藏失败！',
                                                                code: 400
                                                        }
                                                }

                                        }).catch(err => {
                                                console.log('err', err);
                                        });
                                } else {
                                        ctx.body = {
                                                message: iscollection ? '收藏成功！' : '取消收藏成功！',
                                                code: 200,
                                        }
                                }
                        }
                })
        },
        getCollectList: async (ctx, next) => {
                const { user_id, resource_type } = ctx.request.body;
                const sql = `select * from collection where user_id="${user_id}" and resource_type="${resource_type}";`;
                await query(sql).then(result => {
                        if (result) {
                                ctx.body = {
                                        data: result,
                                        code: 200,
                                }
                        }
                }).catch(err => {
                        ctx.body = {
                                data: [],
                                code: 500
                        }
                })
        },
        setUserInfo: async (ctx, next) => {
                const { avatar, brief_intro, location, gender='男', nickname, user_id } = ctx.request.body;
                let sql = `update users set avatar="${avatar}",brief_intro="${brief_intro}",location="${location}",gender="${gender}",nickname="${nickname}" where user_id='${user_id}'`
                if (avatar == null || avatar == '') {
                        sql = `update users set brief_intro="${brief_intro}",location="${location}",gender="${gender}",nickname="${nickname}" where user_id='${user_id}'`
                }
                await query(sql).then(result => {
                        if (result.affectedRows === 1) {
                                ctx.body = {
                                        message: '修改成功！',
                                        code: 200
                                }
                        } else {
                                ctx.body = {
                                        message: '修改失败！请稍后再试',
                                        code: 500
                                }
                        }
                })

        },
        getMycollectionList: async (ctx, next) => {
                const sql = `SELECT resource_id FROM collection  WHERE user_id = ? and resource_type = ?;`
                await query(sql, [ctx.request.body.resource_id, ctx.request.body.resource_type])
                        .then(async (result) => {
                                if (result.length > 0) {
                                        let sql1
                                        let dataList = []
                                        if (ctx.request.body.resource_type == 'pet') {
                                                sql1 = `select * from cardlist where card_id=?`
                                        } else {
                                                sql1 = `select * from shareposts where shareposts_id=?`
                                        }
                                        for (let index = 0; index < result.length; index++) {
                                                await query(sql1, [result[index].resource_id]).then(res => {
                                                        if (res) {
                                                                dataList = dataList.concat(res)
                                                        }
                                                })

                                        }
                                        ctx.body = {
                                                code: 200,
                                                data: dataList
                                        }
                                } else {
                                        ctx.body = {
                                                code: 200,
                                                data: []
                                        }
                                }
                        }).catch(err => {
                                console.log('err', err);
                                ctx.body = {
                                        code: 500,
                                        message: '服务器错误,请稍后再试'
                                }
                        })
        },
        addhistory: async (ctx, next) => {
                const { viewer_id, browser_id, browser_type } = ctx.request.body;
                console.log(viewer_id, browser_id, browser_type);
                const sql1 = `insert into browserhistory(historyId,viewer_id,browser_id,browser_type,browser_time) values('${uuidv4()}','${viewer_id}','${browser_id}','${browser_type}','${dayjs().format('YYYY-MM-DD HH:mm:ss')}')`;
                const sql = `select * from browserhistory where viewer_id='${viewer_id}' and browser_id='${browser_id}' and browser_type='${browser_type}'`;
                await query(sql).then(async (result) => {
                        if (result.length) {
                                let browser_time = dayjs().format('YYYY-MM-DD HH:mm:ss');
                                const sql2 = `update browserhistory set browser_time='${browser_time}' where viewer_id='${viewer_id}' and browser_id='${browser_id}' and browser_type='${browser_type}'`;

                                await query(sql2).then((result2) => {
                                        if (result2.affectedRows > 0) {
                                                ctx.body = {
                                                        code: 200,
                                                        data: null
                                                }
                                        }

                                })
                        } else {
                                await query(sql1).then(async (result) => {
                                        if (result.length > 0) {
                                                ctx.body = {
                                                        code: 200,
                                                        data: null
                                                }
                                        } else {
                                                ctx.body = {
                                                        code: 500,
                                                        data: null
                                                }
                                        }
                                })
                        }
                })

        },
        getHistory: async (ctx, next) => {
                const { viewer_id, browser_type } = ctx.request.body;
                await query(`select * from browserhistory where viewer_id = '${viewer_id}' and browser_type = '${browser_type}' ORDER BY browser_time DESC;`).then(async (res)=>{
                        console.log(res);
                        if (res.length > 0) {
                                let sql1
                                let dataList = []
                                if (browser_type == 'pet') {
                                        sql1 = `select * from cardlist where card_id=?`
                                } else {
                                        sql1 = `select * from shareposts where shareposts_id=?`
                                }
                                for (let index = 0; index < res.length; index++) {
                                        await query(sql1, [res[index].browser_id]).then(result => {
                                                if (result) {
                                                        dataList = dataList.concat(result)
                                                }
                                        })

                                }
                                ctx.body = {
                                        code: 200,
                                        data: dataList
                                }
                        } else {
                                ctx.body = {
                                        code: 200,
                                        data: []
                                }
                        }
                })
        },
}


module.exports = user;